import { getUserInfo } from "../utils/api";
import { useRequest } from "ahooks";
import { useEffect, useState } from "react";
import useGetUserInfo from "./useGetUserInfo";
import { useDispatch } from "react-redux";
import { loginReducer } from "../store/userReducer";
const useLoadingUseInfo = () => {
  const dispatch = useDispatch();
  const [waitingLoadUser, setWaitingLoadUser] = useState(true);
  const { run } = useRequest(getUserInfo, {
    manual: true,
    onSuccess(res) {
      const { username, nickname } = res;
      dispatch(loginReducer({ username, nickname }));
    },
    onFinally() {
      setWaitingLoadUser(false);
    },
  });

  //判断redux中是否存在信息
  const { username } = useGetUserInfo();
  useEffect(() => {
    if (username) {
      setWaitingLoadUser(false);
      return;
    }
    run();
  }, [username]);

  return { waitingLoadUser };
};

export default useLoadingUseInfo;
